package com.luyuan.framework.security.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.luyuan.common.core.domain.model.LoginUser;
import com.luyuan.common.core.domain.model.WxappLoginUser;
import com.luyuan.common.utils.SecurityUtils;
import com.luyuan.common.utils.StringUtils;
import com.luyuan.framework.web.service.TokenService;
import com.luyuan.framework.web.service.WxappTokenService;

/**
 * 多用户token过滤器 验证token有效性
 * 支持网站用户和微信小程序用户
 * 
 * @author luyuan
 */
@Component
public class MultiUserJwtAuthenticationTokenFilter extends OncePerRequestFilter
{
    @Autowired
    private TokenService tokenService;
    
    @Autowired
    private WxappTokenService wxappTokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        // 首先尝试获取传统的网站用户
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
        {
            tokenService.verifyToken(loginUser);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        else
        {
            // 如果没有获取到网站用户，尝试获取微信小程序用户
            WxappLoginUser wxappLoginUser = wxappTokenService.getWxappLoginUser(request);
            if (StringUtils.isNotNull(wxappLoginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
            {
                wxappTokenService.verifyToken(wxappLoginUser);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(wxappLoginUser, null, wxappLoginUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        chain.doFilter(request, response);
    }
}